package org.example.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.example.JoinGroupRequestPacket;
import org.example.JoinGroupResponsePacket;
import org.example.QuitGroupRequestPacket;
import org.example.QuitGroupResponsePacket;
import org.example.im.SessionUtil;

public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket quitGroupRequestPacket) {
        System.out.println("服务端处理退出群聊的请求逻辑...收到的参数:" + quitGroupRequestPacket);
        // 1、获取群聊id
        ChannelGroup channelGroup = SessionUtil.getGroup(quitGroupRequestPacket.getGroupId());

        // 移除当前连接
        channelGroup.remove(ctx.channel());

        // 2、发送响应报文
        QuitGroupResponsePacket quitGroupResponsePacket = QuitGroupResponsePacket.builder()
                .success(true)
                .userId(SessionUtil.getUserId(ctx.channel()))
                .groupId(quitGroupRequestPacket.getGroupId())
                .build();

        //ctx.channel().writeAndFlush(joinGroupResponsePacket);
        // 此处可以通知群里所有人，有人退群了
        channelGroup.writeAndFlush(quitGroupResponsePacket);
    }
}
